package com.kuangstudy.controller.hyperloglog;

import com.kuangstudy.service.hyperloglog.UvService;
import com.kuangstudy.vo.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/5/25 11:30
 */
@RestController
@Log4j2

public class HyperLogLogUVController {

    @Autowired
    UvService uvService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 统计今天的访问量
     *
     * @return
     */
    @GetMapping("/hyperloglog/uv/day")
    public R uv() {
        String format = new SimpleDateFormat("yyyyMMdd").format(new Date());
        // 1: 通过redis的hyperloglog的pfcount统计今天的uv
        Long aLong = redisTemplate.opsForHyperLogLog().size("uv:" + format);
        return R.ok().data("daycount", aLong).message("今日【" + format + "】访问量是：" + aLong);
    }

    /**
     * 统计一周访问量
     *
     * @return
     */
    @GetMapping("/hyperloglog/uv/week")
    public R uvweek() {
        // 1: 通过redis的hyperloglog的pfcount统计今天的uv
        Long aLong1 = redisTemplate.opsForHyperLogLog().size("uv:20210520");
        Long aLong2 = redisTemplate.opsForHyperLogLog().size("uv:20210521");
        Long aLong3 = redisTemplate.opsForHyperLogLog().size("uv:20210522");
        Long aLong4 = redisTemplate.opsForHyperLogLog().size("uv:20210523");
        Long aLong5 = redisTemplate.opsForHyperLogLog().size("uv:20210524");
        Long aLong6 = redisTemplate.opsForHyperLogLog().size("uv:20210525");
        Long aLong7 = redisTemplate.opsForHyperLogLog().size("uv:20210526");

        Long uvtotal = redisTemplate.opsForHyperLogLog().union("uvtotal",
                "uv:20210520",
                "uv:20210521",
                "uv:20210522",
                "uv:20210523",
                "uv:20210524",
                "uv:20210525",
                "uv:20210526");

        Map<String, Long> map = new HashMap<>();
        map.put("20210520", aLong1);
        map.put("20210521", aLong2);
        map.put("20210522", aLong3);
        map.put("20210523", aLong4);
        map.put("20210524", aLong5);
        map.put("20210525", aLong6);
        map.put("20210526", aLong7);

        return R.ok().data("daycount", map).data("uvtotal", uvtotal);
    }
}
